home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11620 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  52 lines

  1. Path: news.mira.net.au!news
  2. From: davidw@werple.net.au (David White)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: NEWBIE: Returning 0 as refernce
  5. Date: 16 Mar 1996 00:47:44 +1100
  6. Organization: Werple Internet, Melbourne
  7. Message-ID: <4ibse0$369@werple.net.au>
  8. References: <4huslk$rpk@badger.wmin.ac.uk> <4hvglg$v4@news4.digex.net> <4hvnbv$2rl@werple.net.au> <4iabdj$r89@news.ot.centuryinter.net>
  9. NNTP-Posting-Host: werplez.mira.net.au
  10.  
  11. steidl@centuryineter.net writes:
  12.  
  13. >In <4hvnbv$2rl@werple.net.au>, davidw@werple.net.au (David White) writes:
  14. >..
  15. >>I think he wants to know how to return a null reference. The answer is, 
  16. >>you can't. In any case, there will be no difference in speed between 
  17.  
  18. >I don't seem to have any problem returning a null reference.  Using
  19. >gcc ported for OS/2 I tested the following program and it compiled
  20. >without errors (or even warnings) and worked as expected.  To create
  21. >a null reference dereference a null pointer, and to test if a reference is
  22. >null, take its address and compare it to a null pointer.  (I don't know if
  23. >this violates some C++ rule, but it works on every compiler I've used.)
  24.  
  25. >-------------------------------------------------
  26.  
  27. >#include <stdio.h>
  28. >#include <stdlib.h>
  29.  
  30. >int &foo() {
  31. >   // more stuff could go here
  32. >   return *((int *)0); // foo decides to return the "standard error-value"
  33. >};
  34.  
  35. >int main() {
  36. >   int &q = foo();
  37. >   if (&q == (int *)0) {
  38. >      printf("Successfully got null reference\n");
  39. >   };
  40. >   return 0;
  41. >};
  42.  
  43. This works because compilers implement references as pointers. It is not 
  44. supported by C++. A reference is an alias for an object. There is no such 
  45. thing as a null 'int', for example, so there is no such thing as a null 
  46. reference to an 'int'. The effect of dereferencing a null pointer, as 
  47. shown above, is undefined.
  48.  
  49. David White
  50. davidw@werple.mira.net.au
  51.  
  52.